package com.tanhua.server.controller;

import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.CountsVo;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UsersController {

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 查询用户资料
     * @return
     */
    @GetMapping
    public ResponseEntity users(@RequestHeader("Authorization") String token,Long userId){
        //2.向userinfo中设置用户id
        if (userId == null){
            userId = UserHolder.getUserId();
        }

        UserInfoVo userInfo = userInfoService.findById(userId);
        return ResponseEntity.ok(userInfo);
    }

    /**
     * 更新用户资料
     */
    @PutMapping
    public ResponseEntity updateUserInfo(@RequestBody UserInfo userInfo,@RequestHeader("Authorization") String token) {
        userInfo.setId(UserHolder.getUserId());
        userInfoService.update(userInfo);
        return ResponseEntity.ok(null);
    }
    /**
     * 更新头像
     */
    @PostMapping("/header")
    public ResponseEntity updateHeader(MultipartFile headPhoto,
                                       @RequestHeader("Authorization") String token) throws IOException {
        userInfoService.updateHead(headPhoto,UserHolder.getUserId());
        return ResponseEntity.ok(null);
    }
    /**
     * 修改手机号- 1 发送短信验证码
     */
    @PostMapping("/phone/sendVerificationCode")
    public ResponseEntity sendVerificationCode(){
        userInfoService.sendVerificationCode();
        return ResponseEntity.ok(null);
    }
    /**
     * 修改手机号 - 2 校验验证码
     */
    @PostMapping("/phone/checkVerificationCode")
    public ResponseEntity checkVerificationCode(@RequestBody Map map){
        String code = (String) map.get("verificationCode");
        boolean isNew = userInfoService.checkVerificationCode(code);
        Map map1 = new HashMap();
        map1.put("verification",isNew);
        return ResponseEntity.ok(map1);
    }
    /**
     * 保存新手机
     */
    @PostMapping("/phone")
    public ResponseEntity updatephone(@RequestBody Map map){
        userInfoService.updatePhone(map);
        return ResponseEntity.ok(null);
    }
    /**
     * 互相喜欢，喜欢，粉丝 - 统计
     */
    @GetMapping("/counts")
    public ResponseEntity counts(){
        Long userId = UserHolder.getUserId();
        CountsVo vo = userInfoService.counts(userId);
        Map map = new HashMap();
        map.put("eachLoveCount",vo.getEachLoveCount());
        map.put("loveCount",vo.getLoveCout());
        map.put("fanCount",vo.getFanCout());
        return ResponseEntity.ok(map);
    }
}
